package com.study.system.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.study.common.result.Result;
import com.study.common.result.ResultCodeEnum;
import com.study.common.utils.JwtHelper;
import com.study.common.utils.ResponseUtil;
import com.study.model.vo.LoginVo;
import com.study.system.custom.CustomUser;
import com.study.system.service.AsyncLoginLogService;
import com.study.system.utils.IpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 登录过滤器，继承UsernamePasswordAuthenticationFilter，对用户名密码进行登录校验
 * </p>
 *
 */
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {

    private RedisTemplate redisTemplate;

    private AsyncLoginLogService asyncLoginLogService;

    /*
     @Autowired
     private AsyncLoginLogService asyncLoginLogService;
     直接在普通类中使用@Autowired注入bean，会导致注入的对象为null。
     这是因为普通类无法通过@Autowired注入bean，
     使用@Autowired注入bean要求这个类也注入到spring容器中，交给容器管理。
     */

    public TokenLoginFilter(AuthenticationManager authenticationManager,
                            RedisTemplate redisTemplate, AsyncLoginLogService asyncLoginLogService) {
        this.setAuthenticationManager(authenticationManager);
        this.setPostOnly(false);
        //指定登录接口及提交方式，可以指定任意路径
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/system/index/login","POST"));
        this.redisTemplate = redisTemplate;
        this.asyncLoginLogService = asyncLoginLogService;
    }

    /**获取用户名和密码，认证
     * 登录认证
     * @param req
     * @param res
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest req, HttpServletResponse res)
            throws AuthenticationException {
        try {
            LoginVo loginVo = new ObjectMapper().readValue(req.getInputStream(), LoginVo.class);

            Authentication authenticationToken = new UsernamePasswordAuthenticationToken(loginVo.getUsername(), loginVo.getPassword());
            return this.getAuthenticationManager().authenticate(authenticationToken);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 登录成功 - 向前端返回token信息  and   将用户-权限存入redis中
     * @param request
     * @param response
     * @param chain
     * @param auth
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication auth) throws IOException, ServletException {
        //从Authentication中获取用户对象
        CustomUser customUser = (CustomUser) auth.getPrincipal();
        //根据用户id、name产生token
        String token = JwtHelper.createToken(customUser.getSysUser().getId(), customUser.getSysUser().getUsername());
        System.out.println("token:");
        System.out.println(token);

        //保存权限数据，存储用户对应的权限
        redisTemplate.opsForValue().set(customUser.getUsername(), JSON.toJSONString(customUser.getAuthorities()));

        //登陆成功 - 记录日志
        //报错：Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@3940f170]
        //下面这句代码有问题，产生NonePointException
        asyncLoginLogService.recordLoginLog(customUser.getUsername(),1, IpUtil.getIpAddress(request),"登陆成功");

        //返回
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        ResponseUtil.out(response, Result.ok(map));
    }

    /**
     * 认证失败
     * @param request
     * @param response
     * @param e
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        if(e.getCause() instanceof RuntimeException) { //getCause：返回异常的原因
            ResponseUtil.out(response, Result.build(null, 204, e.getMessage()));
        } else {
            ResponseUtil.out(response, Result.build(null, ResultCodeEnum.LOGIN_MOBLE_ERROR));
        }
    }
}
